package com.elcl.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.elcl.storage.ApplicationCache;
import com.elcl.util.ListUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lichunlin on 17/1/27.
 */

public abstract class BaseRvAdapter<T> extends RecyclerView.Adapter {

    protected List<T> list = new ArrayList<T>();
    protected int idLayout;

    public BaseRvAdapter(List<T> list, int idLayout) {
        super();
        this.list = list;
        this.idLayout = idLayout;
    }

    @Override
    public int getItemCount() {
        if (ListUtils.isNotEmpty(list)) {
            return list.size();
        } else {
            return 0;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(
                ApplicationCache.context).inflate(idLayout, parent,
                false));
        return holder;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        // 如果设置了回调，则设置点击事件
        if (mOnItemClickLitener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickLitener.onItemClick(holder.itemView, pos);
                }
            });

            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickLitener.onItemLongClick(holder.itemView, pos);
                    return false;
                }
            });
        }

        getItemView(holder, position);
    }

    public abstract void getItemView(RecyclerView.ViewHolder holder, int position);

    class BaseViewHolder extends RecyclerView.ViewHolder {
        public BaseViewHolder(View view) {
            super(view);
        }
    }


    public interface OnItemClickLitener {
        void onItemClick(View view, int position);

        void onItemLongClick(View view, int position);
    }

    private OnItemClickLitener mOnItemClickLitener;

    public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
        this.mOnItemClickLitener = mOnItemClickLitener;
    }

}
